package com.lyncs.ods.common.exception;

import com.lyncs.ods.common.api.CommonResult;
import com.lyncs.ods.common.web.RequestHolder;
import com.lyncs.ods.constant.LyncsOdsConstant;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局异常处理
 *
 * @author alex
 * @date 2022/01/25
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler implements ResponseBodyAdvice<Object> {

    @ResponseBody
    @ExceptionHandler(value = ApiException.class)
    public CommonResult<?> handle(ApiException e) {
        if (e.getErrorCode() != null) {
            return CommonResult.failed(e.getErrorCode());
        }
        return CommonResult.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public CommonResult<?> handleValidException(MethodArgumentNotValidException e) {
        return getCommonResult(e.getBindingResult(), e);
    }

    private CommonResult<?> getCommonResult(BindingResult bindingResult2, Exception e) {
        String message = null;
        if (bindingResult2.hasErrors()) {
            FieldError fieldError = bindingResult2.getFieldError();
            if (fieldError != null) {
                message = fieldError.getField() + fieldError.getDefaultMessage();
            }
        }
        return CommonResult.validateFailed(message);
    }

    @ResponseBody
    @ExceptionHandler(value = BindException.class)
    public CommonResult<?> handleValidException(BindException e) {
        return getCommonResult(e.getBindingResult(), e);
    }

    @ResponseBody
    @ExceptionHandler(value = WxErrorException.class)
    public CommonResult<?> handleValidException(WxErrorException e) {
        return CommonResult.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public CommonResult<?> handleException(Exception e) {
        log.error("", e);
        return CommonResult.failed(e.getLocalizedMessage());
    }

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        //请求处理完成后响应前添加 header
        serverHttpResponse.getHeaders().add("Access-Control-Expose-Headers", "*");
        serverHttpResponse.getHeaders().add(LyncsOdsConstant.Header.COOKIE, RequestHolder.getCookie());
        serverHttpResponse.getHeaders().add(LyncsOdsConstant.Header.LANGUAGE, RequestHolder.language());
        serverHttpResponse.getHeaders().add(LyncsOdsConstant.Header.REQUEST_ID, RequestHolder.getData(LyncsOdsConstant.Header.REQUEST_ID));
        RequestHolder.remove();
        return o;
    }
}
